package com.jiangjiang.eshop.logistics.service;

import com.jiangjiang.eshop.common.help.DateHelper;
import com.jiangjiang.eshop.logistics.api.CreateEorderRequest;
import com.jiangjiang.eshop.logistics.api.CreateEorderRequestBuilder;
import com.jiangjiang.eshop.logistics.api.CreateEorderResponse;
import com.jiangjiang.eshop.logistics.api.LogisticApi;
import com.jiangjiang.eshop.order.dto.OrderInfoDTO;
import com.jiangjiang.eshop.wms.dto.LogisticOrderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;

/**
 * @ClassName LogisticsService
 * @Description TODO
 * @Author jhw
 * @Date 2021/7/24 19:16
 * @Version 1.0
 **/
@Slf4j
@Service
public class LogisticsService {

    @Autowired
    private LogisticApi logisticApi;
    @Autowired
    private DateHelper dateHelper;


    /**
     * 申请物流单
     * @param order 销售订单数据
     * @return
     */
    public LogisticOrderDTO applyLogisticOrder(OrderInfoDTO order) {
        try {
            CreateEorderRequest request = CreateEorderRequestBuilder.get()
                    .buildOrderRelatedInfo(order)
                    .buildReceiver(order)
                    .buildGoodsList(order)
                    .buildTotalDataMetric(order)
                    .create();
            CreateEorderResponse response = logisticApi.createEOrder(request);
            return convertLogisticOrder(response);
        }catch (Exception e){
            log.warn("LogisticsService applyLogisticOrder error",e);
        }
        return null;
    }

    /**
     * 物流单数据组装
     * @param response
     * @return
     * @throws ParseException
     */
    private LogisticOrderDTO convertLogisticOrder(CreateEorderResponse response) throws ParseException {
        LogisticOrderDTO logisticOrder = new LogisticOrderDTO();
        logisticOrder.setLogisticCode(response.getLogisticCode());
        logisticOrder.setContent(response.getLogisticOrderContent());
        logisticOrder.setGmtCreate(dateHelper.getCurrentDate());
        logisticOrder.setGmtModified(dateHelper.getCurrentDate());
        return logisticOrder;
    }
}
